package cn.tedu.straw.portal.service.impl;

import cn.tedu.straw.portal.dto.PostCommentDTO;
import cn.tedu.straw.portal.ex.StrawException;
import cn.tedu.straw.portal.mapper.AnswerMapper;
import cn.tedu.straw.portal.mapper.CommentMapper;
import cn.tedu.straw.portal.model.Answer;
import cn.tedu.straw.portal.model.Comment;
import cn.tedu.straw.portal.result.ResultCodeEnum;
import cn.tedu.straw.portal.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-11
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public void post(PostCommentDTO postCommentDTO, Integer userId, String userNickName) {
        //查询答案是否存在
        Answer answer = answerMapper.selectById(postCommentDTO.getAnswerId());
        if (answer == null){
            throw new StrawException(ResultCodeEnum.COMMENT_ERROR);
        }

        Comment comment = new Comment();
        LocalDateTime now = LocalDateTime.now();
        comment.setUserId(userId);
        comment.setUserNickName(userNickName);
        comment.setAnswerId(postCommentDTO.getAnswerId());
        comment.setContent(postCommentDTO.getContent());
        comment.setGmtCreate(now);
        comment.setGmtModified(now);

        int rows = baseMapper.insert(comment);
        if (rows != 1){
            throw new StrawException(ResultCodeEnum.INSERT_ERROR);
        }

    }
}
